import re
import json
import csv
import requests
import os

path = os.path.join(os.getcwd(), '统计商品')


def get_img(url, name):
    res = requests.get(url).content

    img_path = os.path.join(path, name)
    res_img_path = re.sub(r'/',' ',img_path)
    if res_img_path:
        with open(res_img_path+'.png', 'wb') as f:
            f.write(res)
    else:
        with open(img_path+'.png', 'wb') as f:
            f.write(res)





writer_csv = os.path.join(path, '统计')
file = open(writer_csv+'.csv', 'w', encoding='utf-8-sig', newline='')
csv_file = csv.writer(file)
f = open('test.json','r',encoding='utf-8').read()

csv_file.writerow(['品名','月销量','获赞','单位','最低价','折扣','简介','商品图链接'])


data = json.loads(f)
data = data['data']['food_spu_tags']
result = []
for i in data:
    type_name = i['name'] # 分类名称
    spus_list = i['spus'] # 商品内容
    csv_file.writerow([type_name+'-----']*10)
    for spus in spus_list:
        month_saled_content = spus['month_saled_content']# 月销量
        praise_content = spus['praise_content']# 商品获赞数
        unit = spus['unit']# 单位
        min_price = spus['min_price']# 最低价
        name = spus['name']# 商品名称
        promotion_info = spus['promotion_info']# 折扣
        description = spus['description']# 简介
        picture = spus['picture']# 商品图
        picture = re.findall('(.*)@.*',picture)
        print('商品名称：{}\n'
              '月销量：{}\n'
              '获赞数：{}\n'
              '单位：{}\n'
              '最低价：{}\n'
              '折扣：{}\n'
              '商品图：{}\n'
              '简介：{}'.format(name, month_saled_content, praise_content, unit, min_price, promotion_info, picture,
                             description))
        print('*' * 100)
        print()

        if picture:
            picture = get_img(picture[0], name)

        csv_file.writerow([name, month_saled_content,praise_content,unit,min_price,promotion_info,description,picture])


